/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import {
  BaseUtilService,
  compareVersion,
  DataMap,
  I18NService
} from 'app/shared';
import { isUndefined } from 'lodash';
import { Subject } from 'rxjs';

@Component({
  selector: 'aui-advanced-parameter',
  templateUrl: './advanced-parameter.component.html',
  styleUrls: ['./advanced-parameter.component.less']
})
export class AdvancedParameterComponent implements OnInit {
  resourceData;
  resourceType;
  formGroup: FormGroup;
  valid$ = new Subject<boolean>();
  dataMap = DataMap;
  scriptErrorTip = {
    ...this.baseUtilService.scriptNameErrorTip,
    invalidMaxLength: this.i18n.get('common_valid_maxlength_label', [8192])
  };
  scriptPlaceholder;
  scriptTooltip;
  osType;
  isCluster = false;
  isSupportedVersion = false;

  constructor(
    private fb: FormBuilder,
    public baseUtilService: BaseUtilService,
    private i18n: I18NService
  ) {}

  ngOnInit() {
    this.initForm();
    this.updateData();
  }

  initForm() {
    this.formGroup = this.fb.group({
      physical_fine_grained: new FormControl(this.isSupportedVersion)
    });
  }

  initData(data: any, resourceType: string) {
    this.resourceData = data;
    this.resourceType = resourceType;
    this.isCluster = data.subType === DataMap.Resource_Type.DWS_Cluster.value;
    if (this.isCluster) {
      this.isSupportedVersion = compareVersion(data.version, '8.1.0') !== -1;
    }
  }

  updateData() {
    if (!this.resourceData?.protectedObject?.extParameters) {
      return;
    }
    const extParameters: any =
      this.resourceData.protectedObject.extParameters || {};
    this.formGroup.patchValue({
      physical_fine_grained: !isUndefined(extParameters?.physical_fine_grained)
        ? extParameters?.physical_fine_grained
        : this.isSupportedVersion
    });
  }

  onOK() {
    if (!this.isCluster) {
      return {};
    }
    return {
      dws_ext_parameters: {
        physical_fine_grained: this.formGroup.get('physical_fine_grained').value
      }
    };
  }
}
